package sz.com.postoffice.jxyzwgcase.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.json.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import sz.com.postoffice.jxyzwgcase.core.CommonResult;
import sz.com.postoffice.jxyzwgcase.core.TableDataInfo;
import sz.com.postoffice.jxyzwgcase.pojo.CollectStatisticsByMonthByCustomer;
import sz.com.postoffice.jxyzwgcase.pojo.Customer;
import sz.com.postoffice.jxyzwgcase.pojo.CustomerInterview;
import sz.com.postoffice.jxyzwgcase.pojo.CustomerInterviewDetail;
import sz.com.postoffice.jxyzwgcase.service.CollectCustomerService;
import sz.com.postoffice.jxyzwgcase.service.CustomerService;
import sz.com.postoffice.jxyzwgcase.utils.ExportWord;

/**
 * @ClassName OrgController
 * @Deacription TODO
 * @Author liuyi
 * @Date 2020/10/23 13:58
 * @Version 1.0
 **/
@Api(value = "ADO集成客户信息收集表", tags = "{ ADO集成客户信息收集表 }")
@RestController
@RequestMapping(value = "/customer")
public class CustomerController {

	@Resource
	private CustomerService customerService;

	@Resource
	private CollectCustomerService collectCustomerService;

	@ApiOperation(value = "根据id查询企业详情", notes = "根据id查询企业详情")
	@RequestMapping(value = "/customerInfo", method = RequestMethod.GET)
	public Customer findByPrimaryKey(Customer customer) {
		System.out.println("开始查询...");
		return customerService.findByPrimaryKey(customer.getId());
	}

	@ApiOperation(value = "导出所选企业数据", notes = "导出所选企业数据")
	@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
	@ResponseBody
	public void downloadFile(HttpServletRequest request, HttpServletResponse response, Customer c) {
		System.out.println("开始查询...");
		String ids = c.getIds();
		@SuppressWarnings("unchecked")
		List<String> list = Arrays.asList(ids.split(","));
		ExportWord word = new ExportWord("UTF-8");
		Map<String, Object> customerMap =getTempMap(customerService.findAllSelected(list));
		try {
			word.exportDoc(response, "exportExcle.ftl", customerMap);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	@ApiOperation(value = "统计企业业务量", notes = "统计企业业务量")
	@RequestMapping(value = "/single", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult single(CollectStatisticsByMonthByCustomer customer) {
		CommonResult results = new CommonResult();
		List<CollectStatisticsByMonthByCustomer> list = collectCustomerService.collectData(customer.getId());
		results.setData(list);
		return results;
	}

	private Map<String, Object> getTempMap(List<Customer> customerList) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> dataList = new ArrayList<>();
		for (Customer customer : customerList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("enterpriseName", customer.getEnterpriseName());
			map.put("enterpriseAddress", customer.getEnterpriseAddress());
			map.put("enterprisePhone", customer.getEnterprisePhone());
			map.put("keyLinkManName", customer.getKeyLinkManName());
			map.put("keyLinkManPosition", customer.getKeyLinkManPosition());
			map.put("keyLinkManPhone", customer.getKeyLinkManPhone());
			map.put("industryType", getValue(customer.getIndustryType(),customer.getIndustryType1()));
			map.put("marketType", getValue(customer.getMarketType(),customer.getMarketType1()));
			map.put("area", getValue(customer.getArea(),""));
			map.put("shipmentType", getValue(customer.getShipmentType(),customer.getShipmentType1()));
			map.put("scale", customer.getScale());
			map.put("customerRequire", getValue(customer.getCustomerRequire(),customer.getCustomerRequire1()));
			map.put("competitorName", getValue(customer.getCompetitorName(),customer.getCompetitorName1()));
			map.put("competitorStatus", customer.getCompetitorStatus());
			map.put("competitorDetail", customer.getCompetitorDetail());
			map.put("customerDemand", customer.getCustomerDemand());
			map.put("customerDemandDegree", customer.getCustomerDemandDegree());
			Integer num = 0;
			List<Map<String, Object>> list = new ArrayList<>();
			for (CustomerInterview interview : customer.getInterviewList()) {
				num++;
				if(num == 1) {
					map.put("userCode", interview.getUserCode());
					map.put("userName", interview.getUserName());
					map.put("interviewTime", interview.getInterviewTime());
					for (CustomerInterviewDetail interviewDetail : interview.getInterviewDetails()) {
						Integer formId = interviewDetail.getFormId();
						if ("radio".equals(interviewDetail.getType())) {
							String dataFixed = interviewDetail.getDataFixed();
							JSONArray arr = new JSONArray(dataFixed);
							for (Object object : arr) {
								JSONObject json = new JSONObject((Map<String, Object>) object);
								if (interviewDetail.getContent().replaceAll("\"", "").equals(json.getString("name"))) {
									map.put(interviewDetail.getLabel(), json.getString("label"));
								}
							}
						} else {
							if("走访记录".equals(interviewDetail.getLabel())) {
								map.put(interviewDetail.getLabel()+(51-formId), interviewDetail.getContent()!=null ? interviewDetail.getContent().replaceAll("\"", ""):"");
							} else if("走访打卡".equals(interviewDetail.getLabel())){
								JSONArray arr = new JSONArray(interviewDetail.getContent().replace("\"[", "[").replace("\"]", "]").replace("\\", ""));
								JSONObject js = new JSONObject((Map<String, Object>) arr.get(0));
								map.put(interviewDetail.getLabel()+(51-formId), js.getString("address").replace("\"", ""));
							} else {
								map.put(interviewDetail.getLabel(), interviewDetail.getContent()!=null ? interviewDetail.getContent().replaceAll("\"", ""):"");
							}
						}
					}
				} else {
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("userCode", interview.getUserCode());
					map1.put("userName", interview.getUserName());
					map1.put("interviewTime", interview.getInterviewTime());
					for (CustomerInterviewDetail interviewDetail : interview.getInterviewDetails()) {
						Integer formId = interviewDetail.getFormId();
						if ("radio".equals(interviewDetail.getType())) {
							String dataFixed = interviewDetail.getDataFixed();
							JSONArray arr = new JSONArray(dataFixed);
							for (Object object : arr) {
								JSONObject json1 = new JSONObject((Map<String, Object>) object);
								if (interviewDetail.getContent().replaceAll("\"", "").equals(json1.getString("name"))) {
									map1.put(interviewDetail.getLabel(), json1.getString("label"));
								}
							}
						} else {
							if("走访记录".equals(interviewDetail.getLabel())) {
								map1.put(interviewDetail.getLabel()+(51-formId), interviewDetail.getContent()!=null ? interviewDetail.getContent().replaceAll("\"", ""):"");
							} else if("走访打卡".equals(interviewDetail.getLabel())){
								JSONArray arr = new JSONArray(interviewDetail.getContent().replace("\"[", "[").replace("\"]", "]").replace("\\", ""));
								JSONObject js = new JSONObject((Map<String, Object>) arr.get(0));
								map1.put(interviewDetail.getLabel()+(51-formId), js.getString("address").replace("\"", ""));
							}else {
								map1.put(interviewDetail.getLabel(), interviewDetail.getContent()!=null ? interviewDetail.getContent().replaceAll("\"", ""):"");
							}
						}
					}
					list.add(map1);
				}
			}
			map.put("interviewList", list);
			dataList.add(map);
		}
		result.put("dataList", dataList);
		return result;
	}

    @ApiOperation(value = "根据条件查询列表", notes = "根据条件查询列表")
    @RequestMapping(value = "/getCustomerList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public TableDataInfo searchList(@RequestBody Customer customer) {
        TableDataInfo tableDataInfo = customerService.findBySelected(customer);
        return tableDataInfo;
    }
    
    // 字符串数组转字符串
 	private String getValue(String str,String other) {
 		String result = str;
 		if (other==null || other.length() == 0) {
 			other = "";
 		}
 		if (str!=null && str.length()>0) {
 			JSONArray arr = new JSONArray(str);
 			result = arr.join("，").replace("\"", "").replaceAll("其他", other);
 		}
 		return result;
 	}
}
